package org.xserver.component.handler.ext.websocket;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;
import org.xserver.component.core.XServerHttpContextAttachment;
import org.xserver.component.handler.ext.AbstractWriteHandler;
import org.xserver.component.handler.ext.WriteHandlerFactory.ResponseType;

@Component
public class WebsocketWriteHandler extends AbstractWriteHandler {

	@Override
	protected Object getContent(XServerHttpContextAttachment attachment,
			Object obj) {
		return new TextWebSocketFrame(ChannelBuffers.copiedBuffer(
				obj.toString(), DEFAULT_CONTENT_CHARSET));
	}

	@Override
	protected ChannelFutureListener getListener(
			XServerHttpContextAttachment attachment, Object obj) {
		return null;
	}

	@Override
	protected ChannelFuture doWrite(XServerHttpContextAttachment attachment,
			Object obj) {
		Channel channel = attachment.getChannelHandlerContext().getChannel();
		return channel.write(obj);
	}

	@Override
	public String getResponseType(XServerHttpContextAttachment attachment) {
		return ResponseType.WEBSOCKET.getType();
	}
}
